package FlinkTest.day06;

import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

import java.util.HashMap;

/**
 * ClassName: Flink04_ProcessFun_WordCount
 * Package: FlinkTest.day06
 * Description:
 *
 * @Author ChenJun
 * @Create 2023/4/13 15:48
 * @Version 1.0
 */
public class Flink04_ProcessFun_WordCount {
    public static void main(String[] args) throws Exception {

        //1. 创建流的运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2. 从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //3. 将数据转换为JavaBean对象
        SingleOutputStreamOperator<String> word = streamSource.process(new ProcessFunction<String, String>() {
            @Override
            public void processElement(String value, ProcessFunction<String, String>.Context ctx, Collector<String> out) throws Exception {
                String[] split = value.split(" ");
                for (String s : split) {
                    out.collect(s);
                }
            }
        });

        //4. 将数据转换为二元组
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordToOne = word.process(new ProcessFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void processElement(String value, ProcessFunction<String, Tuple2<String, Integer>>.Context ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
                out.collect(Tuple2.of(value, 1));
            }
        });

        //5. 将相同key进行聚合
        SingleOutputStreamOperator<Tuple2<String, Integer>> result = wordToOne.process(new ProcessFunction<Tuple2<String, Integer>, Tuple2<String, Integer>>() {

            // 创建k  v  类型
            HashMap<String, Integer> count = new HashMap<String, Integer>();

            @Override
            public void processElement(Tuple2<String, Integer> value, ProcessFunction<Tuple2<String, Integer>, Tuple2<String, Integer>>.Context ctx, Collector<Tuple2<String, Integer>> out) throws Exception {

                //判断是否包含key
                if (count.containsKey(value.f0)) {
                    Integer integer = count.get(value.f0);
                    integer += 1;
                    count.put(value.f0, integer);
                } else {
                    count.put(value.f0, 1);
                }
                out.collect(Tuple2.of(value.f0, count.get(value.f0)));
            }

        });

        result.print();

        env.execute();


    }
}
